package com.tocean.app.config;


import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;
import java.util.function.Supplier;

@Component
public class AutoFillEntityHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        strictInsertFill(metaObject, "createdBy", String.class, "1");
        strictInsertFill(metaObject, "createdByName", String.class, "1");
        strictInsertFill(metaObject, "createDate", LocalDateTime.class, LocalDateTime.now());
        strictInsertFill(metaObject, "lastModifiedBy", String.class, "1");
        strictInsertFill(metaObject, "lastModifiedDate", LocalDateTime.class, LocalDateTime.now());
        strictInsertFill(metaObject, "isDel", Boolean.class, Boolean.FALSE);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        strictUpdateFill(metaObject, "lastModifiedBy", String.class, "2");
        strictUpdateFill(metaObject, "lastModifiedDate", LocalDateTime.class, LocalDateTime.now());
    }

    @Override
    public MetaObjectHandler strictFillStrategy(MetaObject metaObject, String fieldName, Supplier<Object> fieldVal) {
        Object obj = fieldVal.get();
        if (Objects.nonNull(obj)) {
            metaObject.setValue(fieldName, obj);
        }
        return this;
    }

}
